#!/usr/bin/python

import sys,os
from bisect import bisect
import openfst
from scipy import *
import random

def rsamp(a):
    c = cumsum(a)
    return bisect(c,random.uniform(0.0,1.0))


fst = openfst.Read(sys.argv[1])
openfst.Verify(fst)

def gen1():
    result = ""
    state = fst.Start()
    for index in range(64):
        assert state>=0
        n = fst.NumArcs(state)
        if n==0: break
        if len(result)>20 and fst.IsFinal(state) and random.uniform(0,1)<0.1: break
        costs = array([fst.GetWeight(state,j) for j in range(n)])
        probs = exp(-costs)
        probs /= sum(probs)
        j = rsamp(probs)
        olabel = fst.GetOutput(state,j)
        if olabel<0 or olabel>255:
            print "??? olabel=",olabel
            olabel = ord("~")
        result += chr(olabel)
        state = fst.GetNext(state,j)
    return result

for i in range(20):
    print gen1()
